#include "qrulemodel.h"

#include <stdio.h>
#include <stdlib.h>

QRuleModel::QRuleModel(vector<Rule> *rls, QObject* parent) : QAbstractTableModel(parent)
{
    rules = rls;
    //(*rules)[0].rule_name = "new rule name changed in qrulemodel";


}

int QRuleModel::rowCount(const QModelIndex &index) const
{
    return rules->size();

}

int QRuleModel::columnCount(const QModelIndex &index) const
{
    return 5;
}


// returns the item of data that corresponds to the index argument
QVariant QRuleModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    if (index.row() < 0 || index.row() >= rules->size())
        return QVariant();

    Rule rule = rules->at(index.row());

    if(role==Qt::CheckStateRole) {
        if(index.column()==0)
            return rule.enabled ? Qt::Checked : Qt::Unchecked;
    }    

    if (role == Qt::DisplayRole) {
        switch(index.column()) {
             case 1:
            return rule.discogs_lookup.c_str();

             case 2:
            return rule.rule_name.c_str();

             case 3:
            return (Vars::get_action(rule.action)).c_str();

             case 4:
            return rule.to_dir.string().c_str();

             default:
            return QVariant();
        }
    }
    return QVariant();
}

QVariant QRuleModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(role!=Qt::DisplayRole)
        return QVariant();

    if (role != Qt::DisplayRole)
        return QVariant();

    if (orientation == Qt::Horizontal) {
        switch (section) {
             case 0:
            return tr("Id");

             case 1:
            return tr("Discogs Lookup");

             case 2:
            return tr("Rule Name");

             case 3:            
            return tr("Action");

             case 4:
            return tr("To Dir");

             default:
            return QVariant();
        }
    }
    return QVariant();
}


bool QRuleModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (index.isValid() && role == Qt::EditRole)
    {
        int row = index.row();

        Rule rule;

        /*if(value.canConvert<Rule>()) {
            rule = value.value<Rule>();
            rules->push_back(rule);
            emit dataChanged(index, index);
            return true;
        }*/
    }

    return false;
}



// need to implement this for editable models
Qt::ItemFlags QRuleModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::ItemIsEnabled;

    return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}

bool QRuleModel::insertRows(int position, int rows, const QModelIndex &index)
{
    return true;

}
bool QRuleModel::removeRows(int position, int rows, const QModelIndex &index)
{
    return true;
}

